<template>
  <div class="order-form-container">
    <!-- 3D模拟器：修复props传递，移除冗余的:config，仅保留事件监听 -->
    <el-card shadow="never" class="pallet-card">
      <div class="card-header">
        <span class="card-title">产品3D参考</span>
      </div>
      <pallet-simulator ref="palletSimulator" @config-update="handlePalletUpdate" />
    </el-card>


    <!-- 订单表单：保持结构不变，优化数据联动 -->
    <el-card shadow="never" class="form-card">

      <CustomerSelector v-model="form.customerId" @select="handleCustomerSelect" />

      <el-form :model="form" :rules="rules" label-position="top" ref="orderFormRef">
        <!-- 送货信息 -->
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="期望收货日期" prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" type="date" placeholder="选择日期"
                :disabled-date="disabledPastDates" style="width: 100%" />
            </el-form-item>
            
          </el-col>
          <el-col :span="12">
            <el-form-item label="送货时间" prop="deliveryHour">
              <el-select v-model="form.deliveryHour" placeholder="选择小时 (7:00-18:00)" style="width: 100%">
                <el-option v-for="hour in availableHours" :key="hour" :label="`${hour}:00`" :value="hour" />
              </el-select>
            </el-form-item>
          </el-col>
          
        </el-row>

        <!-- 价格信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单价 (¥)" prop="unitPrice">
              <el-input v-model="form.unitPrice" :disabled="true" style="width: 100%">
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="1" :max="999" style="width: 100%" @change="calculateTotal" />
            </el-form-item>

          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额 (¥)">
              <el-input v-model="form.totalAmount" :disabled="true" style="width: 100%">
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息：修复校验规则中的空格问题 -->
        <el-form-item label="产品用途、备注等其它需求：1. 承载货物描述：（必填）；2. 接受产品细节调剂的方面：（可联系厂家进行单价优惠）；3. 其它：" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="6" placeholder="请输入备注信息" maxlength="500"
            show-word-limit />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="图片备注">
          <el-upload v-model:file-list="form.images" action="/api/upload" list-type="picture-card" :limit="3"
            :on-exceed="handleExceed" :before-upload="beforeUpload" :on-success="handleUploadSuccess">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitProduct">
            提交产品配置
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单确认弹窗：保持不变 -->
    <el-dialog v-model="showConfirmDialog" title="订单确认" width="600px" :close-on-click-modal="false">
      <div v-if="currentProduct">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="产品名称">
            {{ currentProduct.name }}
          </el-descriptions-item>
          <el-descriptions-item label="产品类型">
            {{ currentProduct.sidefork === 0 ? '二面叉' : '四面叉' }}
          </el-descriptions-item>
          <el-descriptions-item label="面板类型">
            {{ currentProduct.panel_leg === 0 ? '板条-原木' : '胶合板-多层板' }}
          </el-descriptions-item>
          <el-descriptions-item label="生产类型">
            {{ currentProduct.customize === 0 ? '二手' : '定制' }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            ¥{{ form.unitPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="数量">
            {{ form.quantity }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="price-summary">
          <h3>总金额：¥{{ form.totalAmount }}</h3>
        </div>
      </div>
      <template #footer>
        
        <el-button @click="showConfirmDialog = false">返回修改</el-button>
        <el-button type="primary" @click="confirmOrder">确认订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 


<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { product_addAPI, order_addAPI } from '@/api/api'
import PalletSimulator from '@/components/PalletSimulator/index.vue' 
import CustomerSelector from '@/components/utils/CustomerSelector.vue' 
 
// 常量定义 
const availableHours = Array.from({  length: 12 }, (_, i) => i + 7) // 7:00-18:00 
 
// 引用声明 
const palletSimulator = ref(null)
const orderFormRef = ref(null)
const showConfirmDialog = ref(false)
const currentProduct = ref(null)
 
// 表单数据 
const form = reactive({
  cid: '', // 客户ID（从CustomerSelector获取）
  deliveryDate: '',
  deliveryHour: '',
  remark: '1.\n2.\n3.\n...',
  images: [],
  quantity: 1,
  unitPrice: 0,
  totalAmount: 0,
  palletConfig: {}
})
 
// 表单验证规则 
const rules = {
  cid: [
    { required: true, message: '请选择客户', trigger: 'blur' }
  ],
  deliveryDate: [
    { required: true, message: '请选择送货日期', trigger: 'blur' }
  ],
  deliveryHour: [
    { required: true, message: '请选择送货时间', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '数量需在1-999之间', trigger: 'blur' }
  ]
}
 
// 计算总金额 
const calculateTotal = () => {
  form.totalAmount  = (parseFloat(form.unitPrice  || 0) * (form.quantity  || 1)).toFixed(2)
}
 
// 监听3D模拟器配置变化 
const handlePalletUpdate = (newConfig) => {
  form.palletConfig  = { ...newConfig }
}
 
// 获取当前产品配置 
const getCurrentPalletConfig = () => {
  if (!palletSimulator.value)  return null 
  try {
    return palletSimulator.value.getFullConfig() 
  } catch (error) {
    return null 
  }
}
 
// 处理客户选择 
const handleCustomerSelect = (customer) => {
  form.cid  = customer.cid  // 将客户ID保存到表单 
}
 
// 提交产品配置 
const submitProduct = async () => {
  try {
    // 表单验证 
    const valid = await orderFormRef.value.validate() 
    if (!valid) return 
 
    // 获取产品配置 
    const cfg = getCurrentPalletConfig()
    if (!cfg) {
      ElMessage.error(' 无法获取产品配置，请检查3D模拟器')
      return 
    }
 
    // 构建产品数据 
    const productData = {
      name: `${cfg.boardLength}*${cfg.beamLength}`, 
      sidefork: cfg.palletType  === 'two' ? 0 : 1,
      panel_leg: cfg.panelType  === 'wooden' ? 0 : 1,
      customize: cfg.productionType  === 'custom' ? 1 : 0,
      t_bottomlayer: cfg.bottomType  === 'support' ? 1 : 0,
      t_leglayout: cfg.palletType  === 'two' ? 
        (cfg.productionType  === 'custom' ? 
          (cfg.beamLayout  === 'three' ? 1 : 2) : 0) : 0,
      tf_boardwing: cfg.wingWidth, 
      f_structure: cfg.legStructure.replace('type',  '').toUpperCase(),
      f_blockheight: cfg.useCustomHeight  ? cfg.blockHeight  : 0,
    }
 
    // API调用 
    const res = await product_addAPI(productData)
    if (!res?.data?.pid) throw new Error('获取产品ID失败')
 
    // 更新状态 
    currentProduct.value  = { 
      ...productData, 
      pid: res.data.pid, 
      price: res.data.price   
    }
    form.unitPrice  = res.data.price.toFixed(2) 
    calculateTotal()
    showConfirmDialog.value  = true 
 
  } catch (err) {
    ElMessage.error(` 提交失败: ${err.response?.data?.message  || err.message}`) 
  }
}
 
// 确认订单提交 
const confirmOrder = async () => {
  try {
    // 验证必填字段 
    if (!form.cid)  throw new Error('请选择客户')
    if (!currentProduct.value?.pid)  throw new Error('无效的产品配置')
 
    // 构建送货时间 
    const eta = new Date(form.deliveryDate) 
    eta.setHours(form.deliveryHour,  0, 0, 0)
 
    // 构建订单数据 
    const orderData = {
      pid: currentProduct.value.pid, 
      cid: form.cid,  // 使用表单中的客户ID 
      eta: eta.toISOString(), 
      quantity: form.quantity, 
      price: parseFloat(form.unitPrice), 
      total_amount: parseFloat(form.totalAmount), 
      remark: form.remark, 
      images: form.images  
        .map(img => img.response?.data?.url  || img.url) 
        .filter(url => url && url.trim()  !== '')
        .join(','),
      status: 0 // 0=待确认 
    }
 
    // API调用 
    await order_addAPI(orderData)
    ElMessage.success(' 订单创建成功!')
    resetForm()
 
  } catch (err) {
    console.error(' 订单提交错误:', err)
    ElMessage.error(` 下单失败: ${err.response?.data?.message  || err.message}`) 
  } finally {
    showConfirmDialog.value  = false 
  }
}
 
// 禁用过去的日期 
const disabledPastDates = (time) => {
  return time.getTime()  < Date.now()  - 86400000 
}
 
// 重置表单 
const resetForm = () => {
  orderFormRef.value?.resetFields() 
  form.cid  = '' // 清空客户ID 
  form.quantity  = 1 
  form.unitPrice  = 0 
  form.totalAmount  = 0 
  form.images  = []
  palletSimulator.value?.reset?.() 
}
 
// 图片上传处理 
const handleExceed = () => ElMessage.warning(' 最多上传3张图片')
const beforeUpload = (file) => {
  const isValid = file.type.startsWith('image/')  && file.size  / 1024 / 1024 < 5 
  if (!isValid) ElMessage.error(' 请上传小于5MB的图片文件')
  return isValid 
}
const handleUploadSuccess = (res, file) => {
  file.url  = res.data?.url  || ''
}
 
// 自动计算总金额 
watch(() => form.quantity,  calculateTotal)
watch(() => form.unitPrice,  calculateTotal)
</script>
 




<style scoped>
/* 样式保持不变，优化细节 */
.order-form-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pallet-card,
.form-card {
  padding: 20px;
  background: #fff;
}

.card-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
  padding-bottom: 10px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.el-form-item {
  margin-bottom: 18px;
}

.price-summary {
  margin-top: 20px;
  text-align: right;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .order-form-container {
    padding: 10px;
  }

  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>